package shiyan2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;

public class shiyan2_2_cli {
    private static DatagramSocket mSocket;

    public static void main(String[] args) {
        try {
            // 1.初始化DatagramSocket
            mSocket = new DatagramSocket();
            mSocket = new DatagramSocket();
            // 2.创建用于发送消息的DatagramPacket
            Scanner scan = new Scanner(System.in);
            while(true) {
                String sendmas = scan.nextLine();
                InetSocketAddress address = new InetSocketAddress("localhost", 8000);
                byte[] sendData = sendmas.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address);
                // 3.向服务端发送消息
                mSocket.send(sendPacket);
                // 4.创建用于接收消息的DatagramPacket
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                // 5.接收服务端消息
                mSocket.receive(receivePacket);
                System.out.println("服务端说:" + funcByteToStr(receiveData));
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            if (mSocket != null) {
                mSocket.close();
            }
        }
    }
    public static String funcByteToStr(byte[] buffer) {
        try {
            int length = 0;
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] == 0) {
                    length = i;
                    break;
                }
            }
            return new String(buffer, 0, length, "UTF-8");
        } catch (Exception e) {
            return "";
        }
    }

}
